package com.tinusgraglin.enclusiv.datalayer

import android.util.Log
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.HttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.ResponseBody
import java.io.IOException
import java.lang.reflect.Type
import java.util.concurrent.TimeUnit

typealias LongList = List<Long>

class RemoteSourceCommunication(val serverUrl: HttpUrl) {

    val client = okhttp3.OkHttpClient().newBuilder()
        .hostnameVerifier { hostname, _ -> serverUrl.host == hostname }
        .callTimeout(5000, TimeUnit.MILLISECONDS)
        .build()

    private val moshi: Moshi = Moshi.Builder()
        .addLast(KotlinJsonAdapterFactory())
        .build()

    val jsonMediaType = "application/json".toMediaType()

    val resultStrLongDataResponseAdapter =
        newResultStrDataPairAdaptor<Long>(Long::class.javaObjectType)
    val resultStrBoolDataResponseAdapter =
        newResultStrDataPairAdaptor<Boolean>(Boolean::class.javaObjectType)
    val resultStrLongListResponseAdapter =
        newResultStrDataPairAdaptor<List<Long>>(Types.newParameterizedType(List::class.java, Long::class.javaObjectType))

    data class ResultStrDataPairResponse<T> (val data: T?, val result: String)

    fun <T>newResultStrDataPairAdaptor(dataType: Type): JsonAdapter<ResultStrDataPairResponse<T>> =
        moshi.adapter(
            Types.newParameterizedTypeWithOwner(this::class.java, ResultStrDataPairResponse::class.java, dataType)
        )

    class UnexpectedResultString : Exception()

    fun templateGet(requestUrl: HttpUrl): ResponseBody {
        val request = Request.Builder()
            .url(requestUrl)
            .build()

        val resp = client.newCall(request).execute()
        Log.d("##DBG 3198", "code $resp.code")

        if(!resp.isSuccessful)
            throw IOException("Request Error: ${resp.code}")

        return resp.body
    }
}